package com.longcom.ui;


import java.util.Timer;
import java.util.TimerTask;

import com.bairuitech.anychat.AnyChatBaseEvent;
import com.bairuitech.anychat.AnyChatCoreSDK;
import com.bairuitech.anychat.AnyChatDefine;
import com.longcom.domain.ConfigEntity;
import com.longcom.service.ConfigService;

import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.ProgressBar;

public class VideoActivity extends Activity implements AnyChatBaseEvent
{
	private int userId;
	private AnyChatCoreSDK anychat;
	private TimerTask mTimerTask;
	private Timer timer = new Timer(true);
	private ProgressBar progressbar_remote;
	private ProgressBar progressbar_local;
	private SurfaceView surface_remote;
	private SurfaceView surface_local;

	private Handler mHandler;

	private boolean bSelfVideoOpened = false; // 本地视频是否已打开
	private boolean bOtherVideoOpened = false; // 对方视频是否已打开
	private boolean bVideoAreaLoaded = false; // 视频区域大小是否加载
	
	private int dwLocalVideoWidth = 0;
	private int dwLocalVideoHeight = 0;
	private int dwRemoteVideoHeight = 0;
	private int dwRemoteVideoWidth = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_video);
		Intent intent = getIntent();
		userId = Integer.valueOf(intent.getStringExtra("userId"));
		initSDK();
		initView();
		
		mTimerTask = new TimerTask()
		{
			
			@Override
			public void run()
			{
				// TODO Auto-generated method stub
				if(mHandler == null)
				{
					return;
				}
				Message message = new Message();
				mHandler.sendMessage(message);
			}
		};
		
		timer.schedule(mTimerTask, 1000, 100);

		mHandler = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				checkVideoStatus();
				setVolum();
				super.handleMessage(msg);
			}
		};
	}

	private void checkVideoStatus()
	{
		if (!bSelfVideoOpened)
		{
			if(anychat.GetCameraState(-1) != 2 && anychat.GetUserVideoWidth(-1) != 0)
			{
				SurfaceHolder holder = surface_local.getHolder();
				holder.setFormat(PixelFormat.RGB_565);
				holder.setFixedSize(anychat.GetUserVideoWidth(-1), anychat.GetUserVideoHeight(-1));
				Surface surface = holder.getSurface();
				anychat.SetVideoPos(-1, surface, 0, 0, 0, 0);
				bSelfVideoOpened = true;
			}
		}
		
		if(!bOtherVideoOpened)
		{
			if(anychat.GetCameraState(userId) != 2 && anychat.GetUserVideoWidth(userId) != 0)
			{
				SurfaceHolder holder = surface_remote.getHolder();
				holder.setFormat(PixelFormat.RGB_565);
				holder.setFixedSize(anychat.GetUserVideoWidth(userId), anychat.GetUserVideoHeight(userId));
				Surface surface = holder.getSurface();
				anychat.SetVideoPos(userId, surface, 0, 0, 0, 0);
				bOtherVideoOpened = true;
			}
		}
		
	}

	private void setVolum()
	{
		progressbar_local.setProgress(anychat.GetUserSpeakVolume(-1));
		progressbar_remote.setProgress(anychat.GetUserSpeakVolume(userId));
	}
	
	private void adjuestVideoSize(int width, int height)
	{
		if (3 * width > 4 * height) {

			dwRemoteVideoHeight = height;
			dwRemoteVideoWidth = (int) (4.0 / 3.0 * dwRemoteVideoHeight);
		} else {
			dwRemoteVideoWidth = width;
			dwRemoteVideoHeight = (int) (3.0 / 4.0 * dwRemoteVideoWidth);
		}
		dwLocalVideoWidth = dwRemoteVideoWidth;
		dwLocalVideoHeight = dwRemoteVideoHeight;
	}

	private void initView()
	{
		// TODO Auto-generated method stub
		progressbar_local = (ProgressBar) findViewById(R.id.progressbar_local);
		progressbar_remote = (ProgressBar) findViewById(R.id.progressbar_remote);
		surface_local = (SurfaceView) findViewById(R.id.surface_local);
		surface_remote = (SurfaceView) findViewById(R.id.surface_remote);

		// 如果是采用Java视频采集，则需要设置Surface的CallBack
		if (AnyChatCoreSDK
				.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_CAPDRIVER) == AnyChatDefine.VIDEOCAP_DRIVER_JAVA)
		{
			surface_local.getHolder().addCallback(AnyChatCoreSDK.mCameraHelper);
		}

		// 如果是采用Java视频显示，则需要设置Surface的CallBack
		if (AnyChatCoreSDK
				.GetSDKOptionInt(AnyChatDefine.BRAC_SO_VIDEOSHOW_DRIVERCTRL) == AnyChatDefine.VIDEOSHOW_DRIVER_JAVA)
		{
			int index = anychat.mVideoHelper.bindVideo(surface_remote
					.getHolder());
			anychat.mVideoHelper.SetVideoUser(index, userId);
		}
		
		surface_remote.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			
			@Override
			public void onGlobalLayout() {
				// TODO Auto-generated method stub
				if(!bVideoAreaLoaded)
				{
					adjuestVideoSize(surface_remote.getWidth(), surface_remote.getHeight());
					bVideoAreaLoaded=true;
				}
			}
		});
		
		SurfaceHolder holder = surface_remote.getHolder();
		holder.setKeepScreenOn(true);
		
		anychat.UserCameraControl(userId, 1);
		anychat.UserSpeakControl(userId, 1);
		ConfigEntity configEntity = ConfigService.LoadConfig(this);	
		
		if(configEntity.videoOverlay != 0)
		{
			surface_local.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		
		AnyChatCoreSDK.mCameraHelper.SelectVideoCapture(AnyChatCoreSDK.mCameraHelper.CAMERA_FACING_FRONT);
		
		anychat.UserCameraControl(-1, 1);
		anychat.UserSpeakControl(-1, 1);
	}

	private void initSDK()
	{
		anychat = new AnyChatCoreSDK();
		anychat.SetBaseEvent(this);
		anychat.mSensorHelper.InitSensor(this);
	}

	@Override
	public void OnAnyChatConnectMessage(boolean bSuccess)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void OnAnyChatLoginMessage(int dwUserId, int dwErrorCode)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void OnAnyChatEnterRoomMessage(int dwRoomId, int dwErrorCode)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void OnAnyChatOnlineUserMessage(int dwUserNum, int dwRoomId)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void OnAnyChatUserAtRoomMessage(int dwUserId, boolean bEnter)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void OnAnyChatLinkCloseMessage(int dwErrorCode)
	{
		// TODO Auto-generated method stub

	}
	
	protected void onPause() {
		super.onPause();
		//bOnPaused = true;
		anychat.UserCameraControl(userId, 0);
		anychat.UserSpeakControl(userId, 0);
		anychat.UserCameraControl(-1, 0);
		anychat.UserSpeakControl(-1, 0);
	}

	protected void onDestroy() {
		super.onDestroy();
		timer.cancel();
		anychat.mSensorHelper.DestroySensor();
		finish();
	}
}
